from kivy.uix.scatter import Scatter
from kivy.properties import NumericProperty, ReferenceListProperty
from kivy.uix.floatlayout import FloatLayout


class GridLayoutEx(FloatLayout):

    _rows = 1
    _cols = 1

    spacing_x = NumericProperty(0)
    spacing_y = NumericProperty(0)
    spacing = ReferenceListProperty(spacing_x, spacing_y)

    def __init__(self, shape=(1, 1), **kwargs):
        super(GridLayoutEx, self).__init__(**kwargs)

        self._cols, self._rows = shape

        if 'spacing' in kwargs:
            self.spacing = kwargs.get('spacing')
        if 'spacing_x' in kwargs:
            self.spacing_x = kwargs.get('spacing_x')
        if 'spacing_y' in kwargs:
            self.spacing_y = kwargs.get('spacing_y')

        self._shape_hint = (1. / self._cols, 1. / self._rows)

    def add_widget(self, widget, col=0, row=0, **kwargs):

        super(GridLayoutEx, self).add_widget(widget)

        origin_pos_x = col * (self.width / self._cols)
        origin_pos_y = row * (self.height / self._rows)

        if 'margin' in kwargs:
            widget.size_hint_x = (self._shape_hint[0] * self.width - kwargs.get('margin')[0] * 2) / self.width
            widget.size_hint_y = (self._shape_hint[1] * self.height - kwargs.get('margin')[1] * 2) / self.height
            origin_pos_x += kwargs.get('margin')[0]
            origin_pos_x += kwargs.get('margin')[1]
        else:
            widget.size_hint = self._shape_hint

        widget.pos = (origin_pos_x, origin_pos_y)


if __name__ == "__main__":
    print ('Run Test')

    from kivy.uix.button import Button
    from kivy.uix.label import Label

    class GridTest(GridLayoutEx):
        def __init__(self, **kwargs):
            super(GridTest, self).__init__((9, 4), **kwargs)

            self.add_widget(Button(text='7'), col=3, margin=(10, 10))
            self.add_widget(Button(text='8'), col=4)
            self.add_widget(Button(text='9'), col=5)
            self.add_widget(Label(text="Hello World"), row=2, col=7)

            print self.width
            print self.height

    from kivy.app import runTouchApp
    from kivy.core.window import Window

    runTouchApp(GridTest(size=Window.size, spacing=(10, 10)))
